package cn.fl.capital.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cmm.user.facade.system.api.IPriorityApiService;
import cmm.user.facade.system.condition.SysUsrFunAuthRQueryCondition;
import cmm.user.facade.system.dto.SysUsrFunAuthRDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.fl.export.api.IRiskExportApiService;
import cn.fl.export.condition.CapFundSummaryExportCondition;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundSummaryQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapFundSummaryDTO;
import cn.fl.capital.service.ICapFundSummaryApiService;
import cn.fl.capital.service.ICapFundSummaryService;
import cn.fl.capital.transform.CapFundSummaryVOTransform;
import cn.fl.capital.vo.CapFundSummaryVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risk.condition.RskAppoRecQueryCondition;
import cn.fl.risk.condition.RskUsrCstRQueryCondition;
import cn.fl.risk.dto.RskUsrCstRDTO;
import cn.fl.risk.service.IRskAppoRecApiService;
import cn.fl.risk.service.IRskUsrCstRApiService;

/**
 * @Description: 客户资金汇总表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class CapFundSummaryServiceImpl implements ICapFundSummaryService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(CapFundSummaryServiceImpl.class);

    /**
     * TODO 自定义 API 暴露服务
     */
    @Autowired
    private ICapFundSummaryApiService capFundSummaryApiService;
    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private IRskAppoRecApiService rskAppoRecApiService;
    @Autowired
    private IRskUsrCstRApiService rskUsrCstRApiService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;

    @Autowired
    private IPriorityApiService priorityApiService;
    @Autowired
    private IRiskExportApiService riskExportApiService;

    @Override
    public CapFundSummaryVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) return null;
        CapFundSummaryDTO dto = this.capFundSummaryApiService.selectCapFundSummaryById(id);
        return CapFundSummaryVOTransform.toVO(dto);
    }

    @Override
    public Long add(CapFundSummaryVO entity) throws BaseException {
        if (null == entity) return null;
        return this.capFundSummaryApiService.addCapFundSummary(CapFundSummaryVOTransform.toDTO(entity));
    }

    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) return false;
        return this.capFundSummaryApiService.removeCapFundSummaryByIds(ids, CurrentThreadContext.getCurrentUserId());
    }

    @Override
    public boolean modify(CapFundSummaryVO entity) throws BaseException {
        if (null == entity) return false;
        return this.capFundSummaryApiService.modifyCapFundSummary(CapFundSummaryVOTransform.toDTO(entity));
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        CapFundSummaryQueryCondition condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new CapFundSummaryQueryCondition());
        }
        condition = (CapFundSummaryQueryCondition) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        page = this.capFundSummaryApiService.searchCapFundSummaryListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<CapFundSummaryVO> voList = CapFundSummaryVOTransform.toVOList((List<CapFundSummaryDTO>) page.getResultList());
            //this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    /*******************************
     * 分页查询罚息管理列表
     * @param page
     * @return
     *******************************/
    @Override
    public Pager searchFineListPage(Pager page) throws BaseException {
        CapFundSummaryQueryCondition condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new CapFundSummaryQueryCondition());
        }
        condition = (CapFundSummaryQueryCondition) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        page = this.capFundSummaryApiService.searchFineListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<CapFundSummaryVO> voList = CapFundSummaryVOTransform.toVOList((List<CapFundSummaryDTO>) page.getResultList());
            //this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    /*******************************
     * 分页查询逾期催收列表
     * @param page
     * @return
     *******************************/
    @Override
    public Pager searchOvdListPage(Pager page) throws BaseException {
        CapFundSummaryQueryCondition condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new CapFundSummaryQueryCondition());
        }
        condition = (CapFundSummaryQueryCondition) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        //condition.setUsrId(161020000100156L);//for test
        page = this.capFundSummaryApiService.searchOvdListPage(page);
        //拼装是否需要提醒+责任人
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<CapFundSummaryVO> voList = CapFundSummaryVOTransform.toVOList((List<CapFundSummaryDTO>) page.getResultList());
            //this.setDictData(voList);
            List cstIdList = null;
            if (CollectionUtils.isNotEmpty(voList)) {
                cstIdList = new ArrayList(voList.size());
                for (CapFundSummaryVO vo : voList) {
                    cstIdList.add(vo.getCstId());
                    vo.setIsRemind(0);
                }
                List<Long> cstList = null;
                Map<Long, SysUsrDTO> cstUsrMap = new HashMap<>();//客户ID:用户

                //我的任务提醒
                if (StringUtils.isNotBlank(condition.getQueryType()) && "3".equals(condition.getQueryType())) {
                    //查询客户需不需要提醒催收人员，预约时间=当天的并且在提醒状态中（PRJ0038）或预约时间为空的
                    RskAppoRecQueryCondition appoRecQueryCondition = new RskAppoRecQueryCondition();
                    //需提醒资产状态
                    Map<String, String> inPrdCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_PRJ_PRD_STS_CD);
                    if (CollectionUtils.isMapNotEmpty(inPrdCdMap)) {
                        List<String> prdStsCdList = new ArrayList<>(inPrdCdMap.size());
                        for (String key : inPrdCdMap.keySet()) {
                            prdStsCdList.add(key);
                        }
                        appoRecQueryCondition.setPrdStsCdList(prdStsCdList);
                    }
                    appoRecQueryCondition.setCstIdList(cstIdList);
                    cstList = rskAppoRecApiService.searchRskAppoRecRemindList(appoRecQueryCondition);
                }

                //组任务查询任务人
                if (StringUtils.isNotBlank(condition.getQueryType()) && "2".equals(condition.getQueryType())) {
                    //查询客户分配的责任人
                    RskUsrCstRQueryCondition usrCstRQueryCondition = new RskUsrCstRQueryCondition();
                    usrCstRQueryCondition.setCstIdList(cstIdList);
                    usrCstRQueryCondition.setIsDel(0);
                    usrCstRQueryCondition.setIsValid(1);
                    List<RskUsrCstRDTO> rList = this.rskUsrCstRApiService.searchRskUsrCstRList(usrCstRQueryCondition);
                    if (CollectionUtils.isNotEmpty(rList)) {
                        Map<Long, Long> cstMap = new HashMap(rList.size());
                        List<Long> usrIdList=new ArrayList<>(rList.size());
                        for (RskUsrCstRDTO usrCstRDTO : rList) {
                            cstMap.put(usrCstRDTO.getCstId(), usrCstRDTO.getUsrId());
                            if(usrIdList.contains(usrCstRDTO.getUsrId())){
                                continue;
                            }
                            usrIdList.add(usrCstRDTO.getUsrId());
                        }
                        SysUsrQueryCondition sysUsrQueryCondition = new SysUsrQueryCondition();
                        sysUsrQueryCondition.setUsrIds(usrIdList);
                        sysUsrQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
                        List<SysUsrDTO> usrList = sysUsrApiService.searchSysUsrList(sysUsrQueryCondition);
                        Map<Long, SysUsrDTO> usrMap = null;
                        if (CollectionUtils.isNotEmpty(usrList)) {
                            usrMap = new HashMap<>(usrList.size());
                            for (SysUsrDTO dto : usrList) {
                                usrMap.put(dto.getId(), dto);
                            }
                        }

                        for (Map.Entry<Long, Long> entry : cstMap.entrySet()) {
                            if (usrMap != null && usrMap.containsKey(entry.getValue())) {
                                cstUsrMap.put(entry.getKey(), usrMap.get(entry.getValue()));
                            }
                        }
                    }
                }

                for (CapFundSummaryVO vo : voList) {
                    if (cstList != null && cstList.contains(vo.getCstId())) {
                        vo.setIsRemind(1);
                    }
                    if (cstUsrMap != null && cstUsrMap.containsKey(vo.getCstId())) {
                        vo.setUsrNm(cstUsrMap.get(vo.getCstId()).getRefRlNm());
                        vo.setUsrId(cstUsrMap.get(vo.getCstId()).getId());
                    }
                }
            }
            page.setResultList(voList);
        }
        return page;
    }

    /***************************
     * 查询逾期金额汇总
     * @param condition
     * @return
     ***************************/
    @Override
    public CapFundSummaryVO selectOvdAmtSummary(CapFundSummaryQueryCondition condition) throws BaseException {
        if (condition == null) {
            condition = new CapFundSummaryQueryCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        return CapFundSummaryVOTransform.toVO(this.capFundSummaryApiService.selectOvdAmtSummary(condition));
    }

    @Override
    public List<CapFundSummaryVO> searchList(CapFundSummaryQueryCondition condition) throws BaseException {
        if (null == condition) condition = new CapFundSummaryQueryCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        List<CapFundSummaryVO> voList = CapFundSummaryVOTransform.toVOList(this.capFundSummaryApiService.searchCapFundSummaryList(condition));
        this.setDictData(voList);
        return voList;
    }

    /**
     * 添加数据字典名称
     *
     * @param voList
     */
    public void setDictData(List<CapFundSummaryVO> voList) {
        if (CollectionUtils.isEmpty(voList)) return;
        /*Map<String, String> _CdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CapFundSummaryConstant.CODE_CD);
        for(CapFundSummaryVO vo:voList){
			if (_CdMap != null && _CdMap.containsKey(vo.getCd())) {
            	vo.setCdNm(_CdMap.get(vo.getCd()));
        	}	
		}*/
    }
    
    /**
     * 批量导出逾期数据
     * @param condition
     * @return
     * @throws BaseException
     */
    public DataResultVO exportOverdueList(CapFundSummaryExportCondition condition) throws BaseException{
    	if(null == condition){
	        condition = new CapFundSummaryExportCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        try {
            DataResultDTO resultDTO=this.riskExportApiService.exportOverdueList(condition);
            if(null==resultDTO){
                return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
            }else{
                return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger,"exportDecomposeList","批量导出逾期数据据失败");
			BaseLogUtils.error(logger, "-", "异常", e);
        } catch (NumberFormatException e) {
            BaseLogUtils.error(logger,"exportDecomposeList","批量导出逾期数据失败");
			BaseLogUtils.error(logger, "-", "异常", e);
        }
        return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
    }

    @Override
    public JSONArray selectRskUserList(SysUsrFunAuthRQueryCondition qc) {
        if(null==qc){
            BaseLogUtils.info(logger, "selectRskUserList", "根据组织机构id 查询功能角色用户 orgidlist参数不能为空!", CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
        }

        List<SysUsrFunAuthRDTO> searchSysUsrFunAuthRDTOList = this.priorityApiService.selectRskUserList(qc);
        JSONArray jsonArray = new JSONArray ();
        if(CollectionUtils.isEmpty(searchSysUsrFunAuthRDTOList)){
            return jsonArray;
        }
        for (SysUsrFunAuthRDTO sysUsrFunAuthRDTO : searchSysUsrFunAuthRDTOList) {
            JSONObject obj = new JSONObject();
            obj.put("usrId", sysUsrFunAuthRDTO.getUsrId());
            obj.put("usrNm", sysUsrFunAuthRDTO.getUsrNm());
            obj.put("roleId", sysUsrFunAuthRDTO.getRoleId());
            obj.put("roleNm", sysUsrFunAuthRDTO.getRoleNm());

            obj.put("orgId", sysUsrFunAuthRDTO.getOrgId());
            obj.put("orgCd", qc.getOrgCd());
            obj.put("orgNm", sysUsrFunAuthRDTO.getOrgNm());
            obj.put("rlNm", sysUsrFunAuthRDTO.getRlNm());
            obj.put("orgDispNm", sysUsrFunAuthRDTO.getOrgDispNm());
            jsonArray.add(obj);
        }
        return jsonArray;
    }
}
